import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store/index";
import { getUserProfiles, wechatPCLogin } from "../request/httpApi";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/index",
  },
  {
    path: "/index",
    name: "Index",
    component: () =>
      import(/* webpackChunkName:"index" */ "../views/index.vue"),
  },
  {
    path: "/goods",
    name: "Goods",
    component: () =>
      import(/* webpackChunkName:"index" */ "../components/Goodsmall.vue"),
  },
  {
    path: "/user",
    redirect: "/user/center",
    name: "User",
    component: () => import(/* webpackChunkName:"index" */ "../views/User.vue"),
    children: [
      {
        path: "/user/center",
        component: () =>
          import(/* webpackChunkName:"index" */ "../components/Center.vue"),
      },
      {
        path: "/user/cart",
        component: () =>
          import(/* webpackChunkName:"index" */ "../components/Cart.vue"),
      },
    ],
  },
  {
    path: "/detail/:pid",
    component: () =>
      import(/* webpackChunkName:"index" */ "../views/Detail.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  routes,
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem("token");
  const userInfo = store.state.userInfo;
  // 微信扫码登录得到的code值
  const wechatCode = to.query.code;
  // 如果token存在并且userInfo为null
  if (token && !userInfo) {
    // 通过Vuex封装的方法获取用户数据
    store.dispatch("getUserInfo");
    // 获取完毕用户数据之后跳转页面
    next();
  } else if (wechatCode && !token) {
    // 通过网络请求通过code值换取token
    wechatPCLogin({ code: wechatCode }).then(res => {
      if (res.code === 0) {
        localStorage.setItem("token", res["x-auth-token"]);
        // 通过vuex中封装的方法获取用户数据
        store.dispatch("getUserInfo").then(res => {
          // 因为地址栏内有code值，所以做这个操作将地址栏的code值去除，只显示正常的值
          router.replace(to.path);
        });
        next();
      }
    });
  } else if (to.path === "/user" && !token) {
    next(from.path);
  } else {
    // 直接跳转
    next();
  }
});

// 解决重复点击vue路由报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};

export default router;
